import { Fragment, h } from 'vue';
import { labelColorMap, selectedLayers, using } from '../common.js';
import { useCommentCore } from '../api/use-comment.js';
import { picState } from '../api/use-task.js';
import { findLayer, selectLayer } from '../api/use-layer-common.js';

const isSameRow = (elem1, elem2) => elem1.offsetTop == elem2.offsetTop;

const addToRow = (result, elem) => {
  const lastRow = R.last(result);
  if (lastRow && isSameRow(lastRow[0], elem)) {
    return (lastRow.push(elem), result);
  }

  return (result.push([elem]), result);
};

const FstSpanElemOffset = spanElem => ({
  top: `${ spanElem.offsetTop }px`,
  left: `${ spanElem.offsetLeft }px`,
});

const HighlightElem = layer => elems => h(
  'span',
  {
    class: ['highlight', selectedLayers.value.includes(layer) ? 'selected' : ''],
    style: Object.assign(
      FstSpanElemOffset(elems[0]),
      {
        width: elems.reduce((result, elem) => result + elem.offsetWidth, 0) + 'px',
        height: elems[0].offsetHeight + 'px',
        'background-color': layer.color,
      }
    )
  }
);

export function SelectionLabel(props) {
  const rows = Array
    .from(document.querySelector('#label-area > p')?.children ?? [])
    .slice(props.layer.start, props.layer.end + 1)
    .reduce(addToRow, []);
  if (!rows.length) { return h('span'); }

  const elem = rows[0][0];

  return h(
    'span',
    {
      class: ['label', props.selected ? 'selected' : ''],
      style: {
        '--color': labelColorMap.value[props.layer.label],
        top: `${ elem.offsetTop - elem.offsetHeight * .8 }px`,
        left: `${ elem.offsetLeft }px`,
        cursor: 'comment' == props.using ? 'cursor' : 'default',
      },
      onPointerdown: R.both(
        () => 'comment' == using.value,
        R.ifElse(
          () => R.compose( R.isNotNil, R.find(R.propEq(props.layer.id, 'layerId')) )(picState.value.comments),
          () => selectLayer('edit', findLayer(props.layer.id, 'comments') ),
          () => useCommentCore(props.layer.id),
        )
      )
    },
    props.layer.label || '请选择'
  );
}

SelectionLabel.props = ['using', 'layer', 'selected'];

export function SelectionHighlight(props) {
  // 第一步，拿到选到的元素
  // 第二步，元素数组转二级数组，第一维为行，第二维为元素
  // 第三步，各行，得知首个元素的 position，还有这些元素加起来的 width
  // 标签添加到首行首字顶部
  const rows = Array
    .from(document.querySelector('#label-area > p')?.children ?? [])
    .slice(props.layer.start, props.layer.end + 1)
    .reduce(addToRow, []);

  return h(Fragment, rows.map(HighlightElem(props.layer)));
}

SelectionHighlight.props = ['layer'];
